'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useChain } from '@/context/ChainContext';
import { useAuthStore } from '@/store/auth';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Shield, AlertCircle } from 'lucide-react';

interface ChainAuthGuardProps {
  children: React.ReactNode;
  requireAuth?: boolean;
}

export function ChainAuthGuard({ children, requireAuth = true }: ChainAuthGuardProps) {
  const router = useRouter();
  const { currentChain, chainConfig } = useChain();
  const { isAuthenticatedForChain, initializeAuthState } = useAuthStore();
  const [isInitialized, setIsInitialized] = useState(false);

  useEffect(() => {
    // Initialize auth state on mount
    initializeAuthState();
    setIsInitialized(true);
  }, [initializeAuthState]);

  const isAuthenticated = isAuthenticatedForChain(currentChain);

  // If not requiring auth, just render children
  if (!requireAuth) {
    return <>{children}</>;
  }

  // Show loading state while initializing
  if (!isInitialized) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
      </div>
    );
  }

  // If not authenticated for current chain, show prompt
  if (!isAuthenticated) {
    return (
      <div className="flex items-center justify-center min-h-screen p-4">
        <Card className="max-w-md w-full">
          <CardHeader className="text-center">
            <div className="flex justify-center mb-4">
              <Shield className="h-12 w-12 text-muted-foreground" />
            </div>
            <CardTitle>Authentication Required</CardTitle>
            <CardDescription>
              You need to authenticate for {chainConfig.displayName} to access this page
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="bg-muted/50 rounded-lg p-4">
              <div className="flex items-start space-x-3">
                <AlertCircle className="h-5 w-5 text-amber-500 mt-0.5" />
                <div className="space-y-1">
                  <p className="text-sm font-medium">Chain-specific authentication</p>
                  <p className="text-xs text-muted-foreground">
                    Each chain requires separate authentication to ensure security
                  </p>
                </div>
              </div>
            </div>
            <Button 
              onClick={() => router.push(`/login?chain=${currentChain}`)}
              className="w-full"
            >
              Login to {chainConfig.displayName}
            </Button>
          </CardContent>
        </Card>
      </div>
    );
  }

  // User is authenticated for current chain
  return <>{children}</>;
}